package com.example.ujsfish.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import com.example.ujsfish.R;
import com.example.ujsfish.database.MyDatabaseHelper;
import com.example.ujsfish.database.PathDatabase;
import com.example.ujsfish.database.PathPoint;
import com.example.ujsfish.database.PathPointDao;
import com.example.ujsfish.model.user.LoginBody;
import com.example.ujsfish.utils.AppNetService;
import com.example.ujsfish.utils.RetrofitManager;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


public class LoginActivity extends AppCompatActivity {

    Button button3,fgPassword,registerAccount;
    EditText mEtPhone, mEtPasswd;
    CheckBox mCBPsd;
    private String TAG = "MainActivity";
    private String SP_PHONE = "sp_phone";
    private String SP_PASSWD = "sp_passwd";
    private String SP_IS_REMEMBER = "sp_is_remember";
    private SharedPreferences sharedPreferences;
    private boolean mIisChecked = false;
    private  boolean isPermission = false;

    PathDatabase pathDatabase;
    PathPointDao pathPointDao;

    RetrofitManager myRetrofitManager = RetrofitManager.getInstance();
    Retrofit myRetrofit = RetrofitManager.getRetrofit();
    AppNetService appNetService = myRetrofitManager.getApiService(AppNetService.class);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        DatabaseInit(this);



        button3 = findViewById(R.id.button3);
        mEtPhone = findViewById(R.id.text_userName);
        mEtPasswd = findViewById(R.id.text_password);

        initUI();//记住密码
        initData();//记住密码



//        editText.setText();
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEtPhone.getText().toString().equals("") || mEtPasswd.getText().toString().equals("")){
                    Toast.makeText(getApplication(),"账号或密码未输入",Toast.LENGTH_SHORT).show();
                }else{
                    button3.setEnabled(false);
                    Call<LoginBody> loginCall = appNetService.postLogin(mEtPhone.getText().toString().trim(), mEtPasswd.getText().toString().trim());
                    loginCall.enqueue(new Callback<LoginBody>() {
                        @Override
                        public void onResponse(Call<LoginBody> call, Response<LoginBody> response) {
                            LoginBody loginBody = response.body();
                            String msg = loginBody.getMsg();
                            if (msg.equals("用户登录成功")){
                                Log.d(TAG, "onResponse: " + msg);
                                Intent intent = new Intent(LoginActivity.this, ChoseDevice.class);
                                startActivity(intent);
                                Toast.makeText(getApplication(),"登录成功",Toast.LENGTH_LONG).show();
                                SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
                                editor.putString("userName",mEtPhone.getText().toString().trim());
                                editor.apply();
                            }else {
                                Toast.makeText(getApplication(),"登录失败" + msg,Toast.LENGTH_LONG).show();
                            }
                            Log.d(TAG, "登录返回的信息为" + response.body().toString());
                            button3.setEnabled(true);
                        }

                        @Override
                        public void onFailure(Call<LoginBody> call, Throwable t) {
                            button3.setEnabled(true);
                        }
                    });

                }


            }
        });

    }

    private void DatabaseInit(Context context ) {
        MyDatabaseHelper helper = new MyDatabaseHelper(context);
        helper.getWritableDatabase();

        pathDatabase = Room.databaseBuilder(this,PathDatabase.class,"Path_database")
                .allowMainThreadQueries()
                .build();
        pathPointDao = pathDatabase.getPathPointDao();
        PathPoint pathPoint = new PathPoint(

                001,1,"E10","W20",1.5f,0.75f,30f);
        //pathPointDao.insertPaths(pathPoint);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /**
     * 自动填充本地的密码
     */
    private void initData(){
        if(sharedPreferences ==null){
            sharedPreferences = getPreferences(Context.MODE_PRIVATE);
        }
        //回写数据
        mEtPhone.setText(sharedPreferences.getString(SP_PHONE,""));
        mEtPasswd.setText(sharedPreferences.getString(SP_PASSWD,""));

        mIisChecked = sharedPreferences.getBoolean(SP_IS_REMEMBER,false);
        mCBPsd.setChecked(mIisChecked);
    }


    /**
     *保存用户，密码到本地
     *
     */
    private void initUI(){
        button3 = findViewById(R.id.button3);
        mEtPhone = findViewById(R.id.text_userName);
        mCBPsd = findViewById(R.id.checkBox);

        //文本改变之后记录用户的电话
        mEtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(mIisChecked){
                    if(sharedPreferences == null){
                        sharedPreferences = getPreferences(Context.MODE_PRIVATE);
                    }
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(SP_PHONE, mEtPhone.getText().toString());
                    editor.apply();
                }
            }
        });

        //文本改变之后记录用户密码
        mEtPasswd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(mIisChecked){
                    if(sharedPreferences == null){
                        sharedPreferences = getPreferences(Context.MODE_PRIVATE);
                    }
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(SP_PASSWD, mEtPasswd.getText().toString());
                    editor.apply();
                }
            }
        });

        mCBPsd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                Log.d(TAG,"状态为：" + isChecked);
                mIisChecked = isChecked;
                if(isChecked){
                    //实例化SharePreferences对象
                    if(sharedPreferences == null){
                        sharedPreferences = getPreferences(Context.MODE_PRIVATE);
                    }

                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(SP_PHONE, mEtPhone.getText().toString());
                    editor.putString(SP_PASSWD, mEtPasswd.getText().toString());
                    editor.putBoolean(SP_IS_REMEMBER, isChecked);
                    editor.apply();
                }

            }
        });

    }





}

